#include"common.h"
using namespace std;

int cmdParser(const int argc, const char * argv[]) {
    bool builtin;

    if(argc == 0)
        return 0;

    if(strcmp("man", argv[0])) {
        builtin = isBuiltinCmd(argv[0]);
        printf("Command: %s, %sbuiltin command\n", argv[0], builtin ? "" : "non-");
        if (builtin == false)return 0;
        printf("options:\n");
        int i;int j;int sum=0;int cmdN,optN,k=0;bool flag=true;
        cmdN=findBuiltinCmd(argv[0]);
         for(i = 1; i < argc; i++) {
            if (argv[i][0]=='-'&&argv[i][1]!='-'){
               j=1;sum=0;
               while (argv[i][j]=='-'||(argv[i][j]>='0'&&argv[i][j]<='9')||(argv[i][j]>='a'&&argv[i][j]<='z')||(argv[i][j]>='A'&&argv[i][j]<='Z')){
                   if (!(i==1&&j==1))printf("\n  ");else printf("  ");
                   optN=findCmdShortOpt(&blt[cmdN],argv[i][j]);
                   printf("-%c, --%s ",blt[cmdN].opt[optN].shortOpt,blt[cmdN].opt[optN].longOpt);
                  j++;
               }
               continue;
            }
            if (argv[i][0]=='-'&&argv[i][1]=='-'){
                if (i!=1) printf("\n  ");else printf("  ");sum=0;
                int j1=2;char *sctr;
                while (argv[i][j1]){*(sctr+j1-2)=argv[i][j1];j1++;}
                optN=findCmdlongOpt(&blt[cmdN],sctr);
                printf("-%c, --%s ",blt[cmdN].opt[optN].shortOpt,blt[cmdN].opt[optN].longOpt);
                continue;          
            }
            if (argv[i][0]!='-'){
                if (sum == 0 && blt[cmdN].opt[optN].paramNum == 1){
                   printf("%s\n",argv[i]);sum++;
                }
                else if (blt[cmdN].opt[optN].paramNum == -1) printf("%s ",argv[i]);
                else if ((sum==1 && blt[cmdN].opt[optN].paramNum==1)||blt[cmdN].opt[optN].paramNum==0){
                    if (flag==true){
                        if (blt[cmdN].opt[optN].paramNum==0)printf("\n");
                        printf("parameter:\n");flag=false;
                    }
                    printf("  [%d]<%s>\n", k++, argv[i]);
                }
                
            }
        }
        if (blt[cmdN].opt[optN].paramNum == -1)printf("\n");
    } else {
        if(argc == 1) {
            printf("Usage: man <command>\n");
            return 1;
        }
        man(NULL, NULL, 1, argv + 1);
    }
    return 0;
}
int main(){
	initBuiltin();
	cmdps();
}